package com.nl.lib_core.tool.coroutines

import kotlinx.coroutines.*

/** 作者: wangfei 创建时间: 2021/12/27 包名: com.nl.lib_core.tool.coroutines 类名: CoroutineScopesKt */
val Default: CoroutineDispatcher = Dispatchers.Default

val IO: CoroutineDispatcher = Dispatchers.IO

val UI: CoroutineDispatcher = Dispatchers.Main

val Unconfined: CoroutineDispatcher = Dispatchers.Unconfined

fun defaultScope(listener: CoroutineExceptionListener? = null) =
    GeneralCoroutineScope(Default, listener)

fun ioScope(listener: CoroutineExceptionListener? = null) = GeneralCoroutineScope(IO, listener)

fun uiScope(listener: CoroutineExceptionListener? = null) = GeneralCoroutineScope(UI, listener)

fun customScope(dispatcher: CoroutineDispatcher, listener: CoroutineExceptionListener? = null) =
    GeneralCoroutineScope(dispatcher, listener)

fun runOnUI(block: suspend CoroutineScope.() -> Unit) = uiScope().launch(block = block)

fun <T> asyncOnUI(block: suspend CoroutineScope.() -> T) = uiScope().async(block = block)

fun runInBackground(block: suspend CoroutineScope.() -> Unit) = ioScope().launch(block = block)

fun <T> asyncInBackground(block: suspend CoroutineScope.() -> T) = ioScope().async(block = block)

suspend fun <T> whitUi(block: action<T>): T = withContext(UI) { block() }

suspend fun <T> withIO(block: action<T>): T = withContext(IO) { block() }

suspend fun <T> withDefault(block: action<T>): T = withContext(Default) { block() }

suspend fun <T> withUnconfined(block: action<T>): T = withContext(Unconfined) { block() }
